/*
 * @(#)AbstractJpaDAO.java   2015.八月.14 09:01 上午
 *
 * Copyright (c) 2015 www.7jia2.com
 *
 * 版权声明： 版权所有 违者必究 2015
 *
 */

package cn.sanshuilin.kst.system.provider.write.dao;

//~--- JDK imports ------------------------------------------------------------

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.Serializable;
import java.util.List;

/**
 * @ClassName: AbstractJpaDao   
 * @Description:DAO 类的基类
 * @Date:2015.八月.14 03:01 下午
 * @version        0.8, 2015.八月.14 03:01 下午
 * @author         xu.wengang@7jia2.com  
 */
public abstract class AbstractJpaDao< T extends Serializable > {
    /** EntityManager */
    @PersistenceContext
    protected EntityManager entityManager;
    /** Class */
    private Class< T > clazz;

    /**
     * @Title:setClazz
     * @Description:
     * @param clazzToSet
     */
    public final void setClazz(final Class< T > clazzToSet){
        this.clazz = clazzToSet;
    }

    /**
     * @Title:findOne
     * @Description:
     * @param id
     * @return
     */
    public T findOne(final long id){
        return entityManager.find(clazz , id);
    }

    /**
     * @Title:findAll
     * @Description:
     * @return
     */
    @SuppressWarnings("unchecked")
    public List< T > findAll(){
        return entityManager.createQuery("from " + clazz.getName()).getResultList();
    }

    /**
     * @Title:create
     * @Description:
     * @param entity
     * @return
     */
    public T create(final T entity){
        entityManager.persist(entity);

        return entity;
    }

    /**
     * @Title:update
     * @Description:
     * @param entity
     * @return
     */
    public T update(final T entity){
        return entityManager.merge(entity);
    }

    /**
     * @Title:delete
     * @Description:
     * @param entity
     */
    public void delete(final T entity){
        entityManager.remove(entity);
    }

    /**
     * @Title:deleteById
     * @Description:
     * @param entityId
     */
    public void deleteById(final long entityId){
        final T entity = findOne(entityId);

        delete(entity);
    }



}
